﻿using System;
using System.Data;
using NHibernate;
using OS.Infrastructure.Domain;
using OS.Infrastructure.Domain.UnitOfWork;
using TaskKernel.Domain.Repository;

namespace TaskKernel.Domain.Nhibernate.NHibernateLayer
{
    public class _UnitOfWork : IUnitOfWork
    {
        private readonly ITransaction _transaction;

        public _UnitOfWork(ISession session)
        {
            Session = session;
            Session.FlushMode = FlushMode.Auto;
            _transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
        }

        public ISession Session { get; private set; }

        #region IUnitOfWork Members

        public ICommandRepository<T> RepositoryCommand<T>() where T : class
        {
            return new Repository<T>(Session);
        }

        public IReadOnlyRepository<T> RepositoryQuery<T>() where T : class
        {
            return new Repository<T>(Session);
        }

        public void Dispose()
        {
            if (Session.IsOpen) Session.Close();
        }

        public void Commit()
        {
            if (!_transaction.IsActive)
                throw new InvalidOperationException("No active transation");
            _transaction.Commit();
        }

        public void Rollback()
        {
            if (_transaction.IsActive)
                _transaction.Rollback();
        }

        #endregion
    }
}